package com.ruoyi.web.controller.task;

import com.ruoyi.common.constant.TemplateConstants;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.task.domain.FhPdTaskImportConfig;
import com.ruoyi.task.domain.ZhTaskImportConfig;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.task.domain.TaskImportConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.task.domain.TaskConfig;
import com.ruoyi.task.service.ITaskConfigService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 任务配置配置Controller
 * 
 * @author ruoyi
 * @date 2025-04-24
 */
@RestController
@RequestMapping("/task/config")
public class TaskConfigController extends BaseController
{
    @Autowired
    private ITaskConfigService taskConfigService;

    /**
     * 查询任务配置配置列表
     */
    @PreAuthorize("@ss.hasPermi('task:config:list')")
    @GetMapping("/list")
    public TableDataInfo list(TaskConfig taskConfig)
    {
        startPage();
        List<TaskConfig> list = taskConfigService.selectTaskConfigList(taskConfig);
        return getDataTable(list);
    }

    /**
     * 导出任务配置配置列表
     */
    @PreAuthorize("@ss.hasPermi('task:config:export')")
    @Log(title = "任务配置配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TaskConfig taskConfig)
    {
        try {
            List<TaskConfig> list = taskConfigService.selectTaskConfigList(taskConfig);
            ExcelUtil<TaskConfig> util = new ExcelUtil<TaskConfig>(TaskConfig.class);
            util.exportExcel(response, list, "任务配置配置数据");
        } catch (Exception e) {
            logger.error("task_config_export error ", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取任务配置配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('task:config:query')")
    @GetMapping(value = "/{taskConfigId}")
    public AjaxResult getInfo(@PathVariable("taskConfigId") Long taskConfigId)
    {
        TaskConfig taskConfig = taskConfigService.selectTaskConfigByTaskConfigId(taskConfigId);
        List<String> timeRangeList = new ArrayList<>();
        timeRangeList.add(taskConfig.getStartTime());
        timeRangeList.add(taskConfig.getStartEnd());
        taskConfig.setTimeRange(timeRangeList);
        List<String> scenarionList = Arrays.asList(taskConfig.getScenariosType().split(",")) ;
        taskConfig.setScenariosTypeList(scenarionList);
        return success(taskConfig);
    }

    /**
     * 新增任务配置配置
     */
    @PreAuthorize("@ss.hasPermi('task:config:add')")
    @Log(title = "任务配置配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TaskConfig taskConfig)
    {
        List<String> timeRangeList = taskConfig.getTimeRange();
        String startTime = timeRangeList.get(0);
        String endTime = timeRangeList.get(1);
        taskConfig.setStartTime(startTime);
        taskConfig.setStartEnd(endTime);
        String scenariosType = String.join(",",taskConfig.getScenariosTypeList());
        taskConfig.setScenariosType(scenariosType);
        taskConfig.setUpdateBy(getUsername());
        taskConfig.setCreateBy(getUsername());
        return toAjax(taskConfigService.insertTaskConfig(taskConfig));
    }

    /**
     * 修改任务配置配置
     */
    @PreAuthorize("@ss.hasPermi('task:config:edit')")
    @Log(title = "任务配置配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TaskConfig taskConfig)
    {
        List<String> timeRangeList = taskConfig.getTimeRange();
        String startTime = timeRangeList.get(0);
        String endTime = timeRangeList.get(1);
        taskConfig.setStartTime(startTime);
        taskConfig.setStartEnd(endTime);
        String scenariosType = String.join(",",taskConfig.getScenariosTypeList());
        taskConfig.setScenariosType(scenariosType);
        taskConfig.setUpdateBy(getUsername());
        return toAjax(taskConfigService.updateTaskConfig(taskConfig));
    }

    /**
     * 删除任务配置配置
     */
    @PreAuthorize("@ss.hasPermi('task:config:remove')")
    @Log(title = "任务配置配置", businessType = BusinessType.DELETE)
	@DeleteMapping("/{taskConfigIds}")
    public AjaxResult remove(@PathVariable Long[] taskConfigIds)
    {
        return toAjax(taskConfigService.deleteTaskConfigByTaskConfigIds(taskConfigIds));
    }

    /**
     * 删除任务配置配置
     */
    @PreAuthorize("@ss.hasPermi('task:config:edit')")
    @Log(title = "任务配置配置", businessType = BusinessType.UPDATE)
    @GetMapping("/status/{status}/{taskConfigIds}")
    public AjaxResult status(@PathVariable Long[] taskConfigIds, @PathVariable String status)
    {
        if(!StringUtils.equals("1", status) && !StringUtils.equals("0", status)){
            return error("参数错误");
        }
        return toAjax(taskConfigService.updateTaskConfigStatusByIds(taskConfigIds, status, getUsername()));
    }

    /**
     * excel批量导入
     */
    @PreAuthorize("@ss.hasPermi('task:config:import')")
    @Log(title = "批量导入", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importExcel(@RequestParam("file")MultipartFile file) throws IOException {
        ExcelUtil<TaskImportConfig> excelUtil = new ExcelUtil<TaskImportConfig>(TaskImportConfig.class);
        List<TaskImportConfig> taskConfigs = excelUtil.importExcel(file.getInputStream());
        String username = getUsername();
        return success(taskConfigService.importTaskConfig(taskConfigs, username));
    }

    /**
     * 总行任务参数配置批量导入功能
     * @param file
     * @return
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('task:config:import')")
    @Log(title = "批量导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importZh")
    public AjaxResult zhImportExcel(@RequestParam("file")MultipartFile file) throws IOException {
        ExcelUtil<ZhTaskImportConfig> excelUtil = new ExcelUtil<>(ZhTaskImportConfig.class);
        List<ZhTaskImportConfig> taskConfigs = excelUtil.importExcel(file.getInputStream());
        String username = getUsername();
        return success(taskConfigService.importZhTaskConfig(taskConfigs, username));
    }

    /**
     * 分行盘点任务参数配置批量导入功能
     * @param file
     * @return
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('task:config:import')")
    @Log(title = "批量导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importFhPd")
    public AjaxResult fhPdImportExcel(HttpServletResponse response, @RequestParam("file")MultipartFile file) throws IOException {
        try {
            ExcelUtil<FhPdTaskImportConfig> excelUtil = new ExcelUtil<>(FhPdTaskImportConfig.class);
            List<FhPdTaskImportConfig> taskConfigs = excelUtil.importExcel(file.getInputStream());
            String username = getUsername();

            if(CollectionUtils.isEmpty(taskConfigs)){
                return error("未获取导入数据");
            }

            List<FhPdTaskImportConfig> result = taskConfigService.importFhPdTaskConfig(taskConfigs,
                    username);
            if (result != null) {
                ExcelUtil<FhPdTaskImportConfig> util = new ExcelUtil<FhPdTaskImportConfig>(
                        FhPdTaskImportConfig.class);
                util.exportExcel(response, result, "盘点任务配置异常数据");
                return null;
            }
            return success();
        } catch (Exception e) {
            logger.error(String.format("fhPdImportExcel user = %s :" ,getUsername()) , e);
            return error(e.getMessage());
        }
    }

    /**
     * 批量导入模板下载
     * @param response
     * @param taskConfig
     */
    @PreAuthorize("@ss.hasPermi('task:config:import')")
    @Log(title = "模板导出", businessType = BusinessType.EXPORT)
    @PostMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response, TaskConfig taskConfig) {
        try {
            String taskType = taskConfig.getTaskType();
            if (StringUtils.equals("1", taskType)) {
                FileUtils.downloadFile(response, "总行任务参数配置.xlsx",
                        TemplateConstants.ZH_TASK_TEMPLATE_PATH);
            } else if(StringUtils.equalsAnyIgnoreCase("2", taskType)) {
                FileUtils.downloadFile(response, "分行任务参数配置.xlsx",
                        TemplateConstants.FH_TASK_TEMPLATE_PATH);
            } else if(StringUtils.equalsAnyIgnoreCase("3", taskType)) {
                FileUtils.downloadFile(response, "盘点任务参数配置.xlsx",
                        TemplateConstants.FH_PD_TASK_TEMPLATE_PATH);
            }
        } catch (Exception e) {
            logger.error("downloadTemplate error ", e);
            throw new RuntimeException("文件导出失败");
        }
    }
}
